package com.xiaot.shopping.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaot.common.constant.ProductConstant;
import com.xiaot.common.utils.PageUtils;
import com.xiaot.common.utils.Query;
import com.xiaot.shopping.product.dao.AttrAttrgroupRelationDao;
import com.xiaot.shopping.product.dao.AttrDao;
import com.xiaot.shopping.product.dao.AttrGroupDao;
import com.xiaot.shopping.product.dao.CategoryDao;
import com.xiaot.shopping.product.entity.AttrAttrgroupRelationEntity;
import com.xiaot.shopping.product.entity.AttrEntity;
import com.xiaot.shopping.product.entity.AttrGroupEntity;
import com.xiaot.shopping.product.entity.CategoryEntity;
import com.xiaot.shopping.product.service.AttrGroupService;
import com.xiaot.shopping.product.service.AttrService;
import com.xiaot.shopping.product.vo.AttrGroupRelationVo;
import com.xiaot.shopping.product.vo.AttrRespVo;
import com.xiaot.shopping.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        getBaseMapper().insert(attrEntity);
        if (ProductConstant.ATTR_TYPE_BASE.getCode().equals(attr.getAttrType())) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.ATTR_TYPE_BASE.getCode() : ProductConstant.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        if (!StringUtils.isEmpty(params.get("key").toString())) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", params.get("key").toString())
                        .or().like("attr_name", params.get("key").toString());
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrRespVo> attrRespVoList = page.getRecords().stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            if ("base".equalsIgnoreCase(attrType)) {
                AttrAttrgroupRelationEntity relation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (relation != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relation.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            if (attrEntity.getCatelogId() != null) {
                CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                if (categoryEntity != null) {
                    attrRespVo.setCatelogName(categoryEntity.getName());
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(attrRespVoList);
        return pageUtils;
    }

    @Override
    public AttrRespVo getInfoById(Long attrId) {
        AttrEntity byId = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(byId, attrRespVo);
        AttrAttrgroupRelationEntity relation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (relation != null) {
            attrRespVo.setAttrGroupId(relation.getAttrGroupId());
        }
        if (byId.getCatelogId() != null) {
            attrRespVo.setCatelogPath(attrGroupService.findCatelogPath(byId.getCatelogId()));
        }
        return attrRespVo;
    }

    @Override
    public void updateAttrById(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        if (ProductConstant.ATTR_TYPE_BASE.getCode().equals(attr.getAttrType())) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            if (attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId())) > 0) {
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Integer attrGroupId) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        if (attrAttrgroupRelationEntities.isEmpty()) {
            return null;
        }
        List<Long> attrIdList = attrAttrgroupRelationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        return this.listByIds(attrIdList);
    }

    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Integer attrGroupId) {
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrGroupId));
        if (attrGroupEntity == null) {
            return null;
        }
        // 所有分组id
        List<Long> allGroupId = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", attrGroupEntity.getCatelogId())).stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
        // 所有分配过的规格参数
        List<AttrAttrgroupRelationEntity> allocatedAttrId = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", allGroupId));

        // 所有不包含已分配的规格参数
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", attrGroupEntity.getCatelogId()).eq("enable", 1).eq("attr_type", 1);
        if (!allocatedAttrId.isEmpty()) {
            queryWrapper.notIn("attr_id", allocatedAttrId.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList()));
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.like("attr_name", key);
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public void saveAttrGroupRelation(AttrGroupRelationVo[] attrGroupRelationVos) {
        attrAttrgroupRelationDao.saveAttrGroupRelation(Arrays.asList(attrGroupRelationVos));
    }
}